define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    $("input[name='row[pay_type]']").on('change', function() {
        var val = $(this).val();
        if(val == 2){
            $(".display_cost_id").slideDown();
        }else{
            $(".display_cost_id").slideUp();
        }
    });

    $(document).on('keyup change focus blur', ".type2name", function () {
        var type2num = 0;
        $(".type2name").each(function () {
            if($(this).val()){
                type2num +=  parseFloat($(this).val());
            }
        });
        if(type2num && type2num > 100){
            layer.msg('百分比不能超过100,请修改');
            $(this).val('');
        }
    });
    $(document).on('mousewheel', "input[type='number']", function () {
        return false;
    });
    //监听文本框改变事件
    $(document).on('focus', ".fieldlist input", function () {
        var tmptxt = $(this).val();
        var tepclass = $(this).attr("class");
        if(tepclass == 'form-control venue_salse desc') return false;
        var prcing_type = 0;
        var val = '';
        if(tepclass == 'form-control venue_salse  pricing_num'){
            var attrite = $(this).attr('attrite');
            var arr = attrite.split("_");
            prcing_type = $(".pricing_type_"+arr[2]+"").val();
        }
        if(tmptxt == 0){
            $(this).val('');
        }else{
            $(this).val(tmptxt.replace(/[^\- \d.]/g,''));
            val = tmptxt.replace(/[^\- \d.]/g,'');
        }
        if(prcing_type == 1){
            $(".round_num_"+arr[2]+"").val(val);
        }
    });
    //监听文本框改变事件
    $(document).on('blur', ".fieldlist input", function () {
        var tmptxt = $(this).val();
        var tepclass = $(this).attr("class");
        if(tepclass == 'form-control venue_salse desc') return false;
        var prcing_type = 0;
        var val = '';
        if(tepclass == 'form-control venue_salse  pricing_num'){
            var attrite = $(this).attr('attrite');
            var arr = attrite.split("_");
            prcing_type = $(".pricing_type_"+arr[2]+"").val();
        }
        if(tmptxt == ''){
            $(this).val(0);
        }else{
            $(this).val(tmptxt.replace(/[^\- \d.]/g,''));
            val = tmptxt.replace(/[^\- \d.]/g,'');
        }
        if(prcing_type == 1){
            $(".round_num_"+arr[2]+"").val(val);
        }
    });
    //获取改变事件
    $(document).on('change', ".pricing_type", function () {
        var val = $(this).val();
        var attrite = $(this).attr('attrite');
        var arr = attrite.split("_");
        if(val == 1){
            $(".pricing_price1_"+arr[2]+"").removeClass("hide");
            $(".pricing_price2_"+arr[2]+"").addClass("hide");
        }else{
            $(".pricing_price1_"+arr[2]+"").addClass("hide");
            $(".pricing_price2_"+arr[2]+"").removeClass("hide");
        }
    });

    //展开隐藏
    $(document.body).on("click", ".btn-toggle", function (e) {
        $("a.btn-node-sub[data-id][data-pid][data-pid!=0].disabled").closest("tr").toggle();
        var that = this;
        var show = $("i", that).hasClass("fa-chevron-down");
        $("i", that).toggleClass("fa-chevron-down", !show);
        $("i", that).toggleClass("fa-chevron-up", show);
        $(".btn-node-sub[data-pid=0]").data("shown", show);
    });
    //显示隐藏子节点
    $(".btn-node-sub").off("click").on("click", function (e) {
        $("a.btn-node-sub[data-pid='" + $(this).data("id") + "']").each(function () {
            $(this).closest("tr").toggle();
        });
        return false;
    });

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'integral/zzw/index',
                    generate_url: 'integral/bookmanager/generate',
                    excel_url: 'integral/zzw/excel',
                    generate_tax_url: 'integral/zzw/generate_tax',
                    add_url: 'finance/extract/week/add',
                    multi_url: 'integral/bookmanager/generate',
                    table: 'finance_extract_week',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                columns: [
                    [
                      {checkbox: true},
                        {field: '', title: __('序号'), formatter: function (value, row, index) {
                                var options = table.bootstrapTable('getOptions');
                                var pageNumber = options.pageNumber;
                                var pageSize = options.pageSize;

                                return (pageNumber - 1) * pageSize + 1 + index;
                            }, operate: false},
                        {
                            field: 'name',
                            title: __('Name'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [],
                            formatter: Controller.api.formatter.view
                        },
                        {                           field: 'operate',
                                            width: "120px",
                                            title: '分组',
                                            table: table,
                                            events: Table.api.events.operate,

                       buttons: [
                    {
                        name: 'detail',
                        title: __('导出排名'),
                        classname: 'btn btn-xs btn-warning ',
                        text:'导出排名',

                        url: 'integral/zzw/paiming',
                        callback: function (data) {
                            Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                        }
                    },
                    {
                        name: 'detail',
                        title: __('外联汇总导出'),
                        classname: 'btn btn-xs btn-warning ',
                        text:'外联汇总导出',

                        url: 'integral/outreach/count_rank',
                        callback: function (data) {
                            Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                        }
                    },
                                {
                                    name: 'detail',
                                    title: __('大区排名'),
                                    classname: 'btn btn-xs btn-primary ',
                                    text:'大区排名',

                                    url: 'integral/zzw/daqu',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                }
                                ,
                            {
                                name: 'detail',
                                title: __('分组排名'),
                                classname: 'btn btn-xs btn-primary btn-addtabs',
                                text:'分组排名',
                                url: 'integral/zzw/ranking',
                                callback: function (data) {
                                    Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                }
                            }
                            ,
                            {
                                name: 'detail',
                                title: __('外联排名'),
                                classname: 'btn btn-xs btn-primary btn-addtabs',
                                text:'外联排名',
                                url: 'integral/outreach/rank',
                                callback: function (data) {
                                    Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                }
                            }
                            ,
                            {
                              name: 'detail',
                              title: __('图书经理排名'),
                              classname: 'btn btn-xs btn-primary btn-addtabs',
                              text:'图书经理排名',
                              url: 'integral/manager/index',
                              callback: function (data) {
                                Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                              }
                            }
                           ],
                            formatter: Table.api.formatter.operate

                        },
                      {
                        field: 'operate',
                        width: "120px",
                        title: '送样完成情况统计排行',
                        table: table,
                        events: Table.api.events.operate,
                        buttons: [
                          {
                            name: 'detail',
                            title: __('送样完成情况'),
                            text: __('送样完成情况'),
                            classname: 'btn btn-xs btn-primary btn-addtabs',
                            icon: 'fa fa-list',
                            url: 'integral/bookmanager/stat',
                            callback: function (data) {
                              Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                            }
                          }
                        ],
                        formatter: Table.api.formatter.operate
                      },

                        {field: 'start_time', title: __('Start_time')},
                        {field: 'end_time', title: __('End_time')},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        fenzu:function(){

            $("#append").click(function () {
                $("#fieldlist").find('.hidden').eq(0).removeClass('hidden');


            });
            $(".btn-removes").on('click',function () {
                var dd = $(this).parent('dd');
                var sid = dd.find('select').attr('id');
                $("#"+sid).selectpicker('val','');
                $("#"+sid).selectpicker('refresh');
                $(dd).addClass('hidden');
            })

            $('#sel1').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
               var cs = merge(1);
                if (isSelected==1){
                    var val = $("#sel1").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                       var s1 = removes(val,$("#sel1").selectpicker('val'));
                       $("#sel1").selectpicker('val',s1);
                    }

               }
            });

            $('#sel2').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(2);
                if (isSelected==1){
                    var val = $("#sel2").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel2").selectpicker('val'));
                        $("#sel2").selectpicker('val',s1);
                    }

                }
            });
            $('#sel3').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(3);
                if (isSelected==1){
                    var val = $("#sel3").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel3").selectpicker('val'));
                        $("#sel3").selectpicker('val',s1);
                    }

                }
            });
            $('#sel4').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(4);
                if (isSelected==1){
                    var val = $("#sel4").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel4").selectpicker('val'));
                        $("#sel4").selectpicker('val',s1);
                    }

                }
            });
            $('#sel5').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(5);
                if (isSelected==1){
                    var val = $("#sel5").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel5").selectpicker('val'));
                        $("#sel5").selectpicker('val',s1);
                    }

                }
            });
            $('#sel6').on('changed.bs.select',function(e, clickedIndex, isSelected, previousValue){
                var cs = merge(6);
                if (isSelected==1){
                    var val = $("#sel6").find('option').eq(clickedIndex).val();
                    if(in_array(val,cs.arr)){
                        var s1 = removes(val,$("#sel6").selectpicker('val'));
                        $("#sel6").selectpicker('val',s1);
                    }

                }
            });
            //数组合并，不合并指定的数组
            function merge(h){
                var arr=[];
                var obj;
               for (var i=1;i<=6;i++){
                   if($("#sel"+i).selectpicker('val')!=null && i!=h) {
                       for (var j = 0; j < $("#sel" + i).selectpicker('val').length; j++) {
                           arr.push($("#sel"+i).selectpicker('val')[j]);
                       }
                   }
                   if (h==i){
                       obj = $("#sel"+i).selectpicker('val');
                   }
               }
               return {arr:arr,obj:obj};
            }
            //php in-array
            function in_array(search,array){
                for(var i in array){
                    if(array[i]==search){
                        return true;
                    }
                }
                return false;
            }
            //删除数组中指定的元素
            function removes(val,arrs) {
                if (arrs === undefined || arrs.length == 0) return [];

                var arr=[];

                for (var i in arrs){
                    if (arrs[i]!=val) {
                        arr.push(arrs[i]);
                    }
                }
                return arr;
            }
            Controller.api.bindevent();



        },

        index2: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'integral/zzw/index2',
                    status_url: 'integral/zzw/status',
                    check_url: 'integral/zzw/check',
                    generate_url: 'integral/zzw/generate',
                    excel_url: 'integral/zzw/excel',
                    generate_tax_url: 'integral/zzw/generate_tax',
                    add_url: 'integral/zzw/add',
                    edit_url: 'integral/zzw/edit',
                    del_url: 'integral/zzw/delete',
                    books_url: 'integral/zzw/finance_books',
                    multi_url: 'finance/extract/week/multi',
                    table: 'finance_extract_week',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: true,
                queryParams: function (params) {
                    //这里可以追加搜索条件
                    var filter = params.filter ? JSON.parse(params.filter) : {}; //判断当前是否还有其他高级搜索栏的条件
                    var op = params.op ? JSON.parse(params.op) : {};
                    //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
                    filter.start_time = Fast.api.query('start_time');
                    op.start_time = "=";
                    filter.end_time = Fast.api.query('end_time');
                    op.end_time = "=";
                    if(Fast.api.query('department')){
                        filter.department = filter.department ? filter.department : Fast.api.query('department');
                        op.department = "FIND_IN_SET";
                    }
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        //{field: 'id', title: __('Id')},
                        {
                            field: 'name',
                            title: __('Name'),
                        },

                        {field: 'start_time', title: '开始时间'},

                        {field: 'end_time', title: '结束时间'},

                        {field:'week_i',title:'周开场次积分'},
                        {field:'ykh_i',title:'应开会积分'},
                        {field:'w_task',title:'周任务积分'},
                        {field:'reserve',title:'预定积分+其他积分'},

                        {field: 'department_text', title: '所属部门'},
                        {
                        field: 'buttons',
                        width: "120px",
                        title: __('操作'),
                        table: table,
                        events: Table.api.events.operate,
                        buttons: [
                            {
                                name: 'addtabs',
                                text: __('导出'),
                                title: __('导出'),
                                classname: 'btn btn-xs btn-warning',
                                url: 'integral/zzw/excel'
                            },
                            {
                                name: 'addtabs',
                                text: __('积分统计'),
                                title: __('积分统计'),
                                classname: 'btn btn-xs btn-warning btn-addtabs',
                                url: 'integral/zzw/statis'
                            },
                          {
                            name: 'addtabs',
                            text: __('外联积分'),
                            title: __('外联积分'),
                            classname: 'btn btn-xs btn-primary btn-dialog',
                            icon: 'fa fa-list',
                            url: 'integral/outreach/outrs/department/{department_text}',
                            callback: function (data) {
                              Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                            },
                            visible: function (row) {
                              //返回true时按钮显示,返回false隐藏
                              return true;
                            }
                          },
                          {
                            name: 'addtabs',
                            text: __('图书经理数据'),
                            title: __('图书经理数据'),
                            classname: 'btn btn-xs btn-warning btn-addtabs',
                            icon: 'fa fa-folder-o',
                            url: 'integral/bookmanager/index'
                          },
                          {
                            name: 'addtabs',
                            text: __('图书经理任务单'),
                            title: __('图书经理任务单'),
                            classname: 'btn btn-xs btn-warning btn-addtabs',
                            icon: 'fa fa-folder-o',
                            url: 'integral/taskbook/index'
                          }
                        ],
                        formatter: Table.api.formatter.buttons,
                      }
                        //{field:"publish",title:"", defaultValue:'ceshi'}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        finance_books: function () {
            Controller.api.bindevent();
        },
        status: function () {
            Controller.api.bindevent();
        },
        public_add: function () {
            Controller.api.bindevent();
        },
        public_edit: function () {
            Controller.api.bindevent();
        },
        generate: function () {
            Controller.api.bindevent();
            Controller.api.week();
        },
        excel: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                if(data == 1){
                    console.log(ret.url);
                    setTimeout(function(){
                        document.location.href = ret.url;
                    },50);
                }else{
                    console.log(data.url);
                    for (var i=0;i<data.length;i++){
                        console.log(data[i].url);
                        window.open(data[i].url,'_blank');
                    }

                }
            }, function(data, ret){
                console.log('错误');
            });
            $("select[name='type']").on('change', function() {
                var val = $(this).val();
                var DefaultsTime = $("#DefaultsTime").val();
                var fa = $(".btn-group.bootstrap-select.date.form-control");
                if(val == 2){
                    $("#c-date").selectpicker('val',DefaultsTime);
                    $("#c-date").removeAttr("multiple");
                    fa.removeClass("show-tick");
                }else{
                    $("#c-date").attr("multiple",'');
                    fa.addClass("show-tick");
                }
                $("#c-date").selectpicker("refresh");
                $("#c-date").selectpicker();
            });
            Controller.api.week();
        },

        generate_tax: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                setTimeout(function(){
                    document.location.href = ret.url;
                },50);
            }, function(data, ret){
                console.log('错误');
            });
            $(document).on('click', '.btn-success', function () {
                $("#submitvalue").val($(this).val());
                // $(".generate_tax").submit();
            });
            Controller.api.week();
        },
        detail: function () {
            $(document).on('click', '.btn-callback', function () {
                Fast.api.close($("input[name=callback]").val());
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            week: function () {
                setTimeout(function(){
                    $("#c-year").selectpicker('refresh');
                },500);
                var DefaultsTime = $("#DefaultsTime").val();
                $(document).on("change", "#c-year", function () {
                    setTimeout(function(){
                        $("#c-date").selectpicker('val',DefaultsTime);
                        $("#c-date").selectpicker("refresh");
                        $("#c-date").selectpicker();
                    },500);
                });
            },
            formatter: {//渲染的方法
                browser: function (value, row, index) {
                    //这里我们直接使用row的数据
                    return '<a class="btn btn-xs btn-browser" href="http://www.baidu.com">1111</a>';
                },
                view: function (value, row, index) {
                    var department =  $('#department option:selected').val();
                    var department_w =  '';
                    if(department) department_w = "&department="+department;
                    //这里手动构造URL
                    url = "integral/zzw/index2?start_time=" + row.start_time+"&end_time="+row.end_time+department_w;
                    //url = "finance/extract/week/index2?name=dsadasd&end_time="+row.end_time;
                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    return '<a href="' + url + '" class="addtabsit" title="' + __("Search %s", value) + '">' + __('Search %s', value) + '</a>';
                },
                zdyname: function (value, row, index) {
                    var table = this.table;
                    // 默认按钮组
                    var buttons = [];
                    buttons.push({
                        name: 'detail',
                        title: row.name,
                        text: row.name,
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs btn-dialog',
                        url: 'finance/extract/week/view'
                    });
                    return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                },
                statusName: function (value, row, index) {
                    if(row.status == 4 || row.status == 3){
                        return '<a class="btn btn-xs btn-dialog btn-ip"> '+row.status_text+ '</a>';
                    }else{
                        return row.status_text;
                    }
                },
                operate: function (value, row, index) {
                    var table = this.table;
                    // 操作配置
                    var options = table ? table.bootstrapTable('getOptions') : {};
                    // 默认按钮组
                    var buttons = $.extend([], this.buttons || []);
                    buttons.push({
                        name: 'books',
                        title: '周开场词积分',
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs',
                        text:'周开场次积分',
                        url: options.extend.books_url
                    });
                    buttons.push({
                        name: 'books',
                        title: '应开会周不开会或开会不足',
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs',
                        text:'应开会周不开会或开会不足',
                        url: options.extend.books_url
                    });
                    buttons.push({
                        name: 'books',
                        title: '在标准场次内',
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs',
                        text:'周任务积分',
                        url: options.extend.books_url
                    });
                    return Table.api.buttonlink(this, buttons, value, row, index, 'operate');

                },

            },
            events: {//绑定事件的方法
                statusName: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        Layer.alert("审核信息: <code>" + row.status_desc + "</code>");
                    }
                },

            }

        }
    };
    return Controller;
});